package com.sn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sn.mapper.ItemMappper;
import com.sn.mapper.NewsMapper;
import com.sn.pojo.News;
import com.sn.pojo.NewsItem;
import com.sn.vo.NewsVo;
import com.sn.vo.PageParams;
import com.sn.vo.PageVo;
import com.sn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsService {
    @Autowired
    NewsMapper newsMapper;
    public Result findAll(PageParams pageParams) {
        PageHelper.startPage(pageParams.getCurrentPage(),pageParams.getPageSize());
        //从数据库中查找并且分页展示数据
        List<NewsVo>newsList=newsMapper.findAll(pageParams.getQueryString());
        if (newsList.size()==0||newsList.isEmpty()){
            return new Result(false,-999,"数据库为空",null);
        }
        System.out.println("分页查询后的列表长度:--->"+newsList.size());
        PageInfo pageInfo=new PageInfo(newsList);
        long total = pageInfo.getTotal();
        PageVo pageVo=new PageVo();
        pageVo.setTotal(total);
        pageVo.setList(newsList);
        return new Result(true,111,"查询成功,返回"+total+"条数据",pageVo);
    }

    @Autowired
    CatchService catchService;
    public Result catchBySid(Integer sId) {

        List<News> news = catchService.getNews(sId);//爬取新闻概览,需要批量写入数据库
        if (news==null||news.isEmpty()){
            return new Result(false,-999,"爬取新闻失败",null);
        }
        for (News n : news) {
            //插入新闻概览会自动产生nId，将得到的id给新闻详情
            String uri = n.getNHref();//先得到链接，爬取详情
            NewsItem item = catchService.getItem(sId, uri);//得到详情
            if (item==null){
                //说明抓取失败
                System.out.println("抓取失败...失败链接: "+uri);
                continue;
            }
            //将两个写入数据库
            n.setSId(sId);
            newsMapper.addNews(n);
            Integer nId = n.getNId();
            item.setNId(nId);//设置nId
            newsMapper.addItem(item);//写入详情
        }
        return new Result(true,111,"爬取成功,新增"+news.size()+"条数据",null);
    }

    @Autowired
    ItemMappper itemMappper;
    public Result deleteByNids(List<Integer> nIds) {
        int s1=newsMapper.deleteByNids(nIds);
        int s2=itemMappper.deleteByNids(nIds);
        int size = nIds.size();
        if(s1==size&&s2==size){
            System.out.println(s1+".."+s2);
            return new Result(true,111,"删除成功",null);
        }
        return new Result(false,-999,"出现错误",null);
    }
}
